package cn.ffcs.uec.outStaffLeaveApply.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zul.Messagebox;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.theme.ThemeDisplay;
import cn.ffcs.uec.common.manager.CustomFilesManager;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.common.vo.UecBdPsncl;
import cn.ffcs.uec.organization.manager.UecOrgDeptManager;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgDept;
import cn.ffcs.uec.organization.vo.OrganizationRelationVo;
import cn.ffcs.uec.outStaff.manager.UecOutStaffManager;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaffLeaveApply.action.bean.OutStaffLeaveApprovalViewMainBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.manager.ActRunTaskManager;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecPsnjobManager;
import cn.ffcs.uec.staff.model.UecPsnjob;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.model.DefaultDaoFactory;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;

@Controller
@Scope("prototype")
public class OutStaffLeaveApprovalViewMainComposer extends BasePortletComposer {

	private static final long serialVersionUID = -6299517135233887515L;

	private OutStaffLeaveApprovalViewMainBean bean = new OutStaffLeaveApprovalViewMainBean();

	private UecOutStaffInfo outStaffInfo = UecOutStaffInfo.newInstance();

	private UecPsnjob uecPsnjob = UecPsnjob.newInstance();

	private UecOutStaffManager uecOutStaffManager = (UecOutStaffManager) ApplicationContextUtil
			.getBean("uecOutStaffManager");

	private UecPsnjobManager uecPsnjobManager = (UecPsnjobManager) ApplicationContextUtil
			.getBean("uecPsnjobManager");

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	private ActRunTaskManager actRunTaskManager = (ActRunTaskManager) ApplicationContextUtil
			.getBean("actRunTaskManager");

	private UecOrgDeptManager uecOrgDeptManager = (UecOrgDeptManager) ApplicationContextUtil
			.getBean("uecOrgDeptManager");

	/**
	 * 选择的组织
	 */
	private OrganizationRelationVo organization;

	/**
	 * 部门
	 */
	private UecOrgDept findUecOrgDept;

	private String taskDefKey;

	private String type;

	private String taskId;

	private AtiOaBaseObject oaBaseObject;

	/**
	 * 外包人员基本信息更新标志
	 */
	private boolean outStaffInfoUpdateFlag = false;

	/**
	 * 人员类别
	 */
	private UecBdPsncl uecBdPsncl;

	/**
	 * 人员类别
	 */
	private UecBdPsncl uecBdPsnclTree;

	private CustomFilesManager customFilesManager = (CustomFilesManager) ApplicationContextUtil
			.getBean("customFilesManager");

	@Override
	public String getPortletId() {
		return super.getPortletId();
	}

	@Override
	public ThemeDisplay getThemeDisplay() {
		return super.getThemeDisplay();
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		Components.wireVariables(comp, bean);

		this.bean.getOutStaffPkDept().addForward("onGetOrganization", comp,
				"onGetOrganizationResponse");
		this.bean.getOutPsncl().addForward("onGetBdPsncl", comp,
				"onGetBdPsnclResponse");
	}

	/**
	 * 界面初始化
	 */
	public void onCreate$outStaffLeaveApprovalViewMainWin() {
		bandListbox();
		bindBean();
	}

	/**
	 * 监听人员类别组织树
	 */
	public void onGetBdPsnclResponse(final ForwardEvent event) {
		if (event.getOrigin().getData() != null) {
			uecBdPsnclTree = (UecBdPsncl) event.getOrigin().getData();
		}
	}

	/**
	 * 监听组织树插件抛出的事件
	 * 
	 * @param event
	 */
	public void onGetOrganizationResponse(final ForwardEvent event) {
		if (event.getOrigin().getData() != null) {
			organization = (OrganizationRelationVo) event.getOrigin().getData();
			if ("ORG".equals(organization.getOrgType())) {
				ZkUtil.showError("转正后部门选项请选择到部门层级!", "错误提示");
				bean.getOutStaffPkDept().setValue(null);
				bean.getPkHrorg().setValue(null);
				return;
			} else {
				// 根据部门主键：pkorg，找到该部门所在的公司
				findUecOrgDept = new UecOrgDept();
				findUecOrgDept.setPkDept(organization.getOrg());
				findUecOrgDept = uecOrgDeptManager
						.findUecOrgDeptByOrgDept(findUecOrgDept);
				if (null != findUecOrgDept) {
					// 组织
					bean.getPkHrorg().setValue(
							uecOrgOrgsManager
									.getUecOrgOrgsNameByPkOrg(findUecOrgDept
											.getPkOrg()));
					// 部门
					bean.getOutStaffPkDept().setValue(
							uecOrgDeptManager
									.getUecOrgDeptNameByPkDept(findUecOrgDept
											.getPkDept()));
				}
			}
		}
	}

	/**
	 * 重新申请
	 * 
	 * @throws InterruptedException
	 */
	public void onOk() throws InterruptedException {

		if (!ApprovalConstants.OP_TYPE_VIEW.equals(type)) {
			// 判断任务是否已被处理
			boolean isCompleted = ApprovalUtil.isTaskCompleted(oaBaseObject,
					taskId);
			if (isCompleted) {
				onCancel();
				Events.postEvent(ApprovalConstants.ON_REFRESH_QUERY_RESPONSE,
						this.self, null);
				ZkUtil.showError("任务不存在或已被处理完毕！", "错误提示");
				return;
			}
			// 数据校验
			String msg = this.checkUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK
					| Messagebox.CANCEL, Messagebox.QUESTION,
					new EventListener() {
						@Override
						public void onEvent(Event event) throws Exception {
							if (((Integer) event.getData()).intValue() == Messagebox.OK) {
								postApprovalData();
								onCancel();
							} else {
								return;
							}
						}
					});
		} else {
			this.onCancel();
		}

	}

	public void postApprovalData() throws InterruptedException {
		String currentName = ApprovalUtil.getCurrentName();
		if (StrUtil.isNullOrEmpty(currentName)) {
			ZkUtil.showError("当前登录用户已失效，请重新登录！", "错误提示");
			return;
		}
		PubUtil.fillPoFromEditorBean(uecPsnjob, bean);
		// 获取人员类别
		if (null != uecBdPsnclTree) {
			String pkpsncl = uecBdPsnclTree.getPkPsncl();
			uecPsnjob.setPkPsncl(pkpsncl);
		}
		// 离职申请
		if (null != uecPsnjob) {
			// 如果触发了事件
			if (null != findUecOrgDept) {
				// 更新人员基本信息中的组织
				if (!outStaffInfo.getPkHrorg()
						.equals(findUecOrgDept.getPkOrg())) {
					outStaffInfo.setPkHrorg(findUecOrgDept.getPkOrg());
					outStaffInfo.setModifier(currentName);
					outStaffInfo.setModifiedTime(DateUtil.getCurrenDate());
					outStaffInfoUpdateFlag = true;
				} else {
					outStaffInfoUpdateFlag = false;
				}
				// 组织、部门
				if (null != findUecOrgDept) {
					uecPsnjob.setPkDept(findUecOrgDept.getPkDept());
					uecPsnjob.setPkHrorg(findUecOrgDept.getPkOrg());
				}
			}
		}
		// 获取生效日期
		String enddate = DateUtil.dateToStr(bean.getEffectDate().getValue());
		uecPsnjob.setEnddate(enddate);
		uecPsnjob.setModifiedtime(DateUtil.getCurrenDate());
		uecPsnjob.setModifier(currentName);
		if (outStaffInfoUpdateFlag) {
			// 更新人员的组织
		}
		DefaultDaoFactory.getDefaultDao().updateObject(uecPsnjob);

		Events.postEvent("onOKResponse", this.self,
				ApprovalConstants.ON_OK_RESULT);

	}

	/**
	 * 审批同意
	 * 
	 * @throws InterruptedException
	 */
	public void onApproval() throws InterruptedException {
		Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							approvalData();
						} else {
							return;
						}
					}
				});
	}

	public void approvalData() {
		Map<String, Object> map = new HashMap<String, Object>();
		String comment = this.getComment(taskDefKey);
		map.put("comment", comment);
		map.put("onApprovalResult", ApprovalConstants.ON_APPROVAL_RESULT);
		Events.postEvent("onApprovalResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 审批拒绝
	 */
	public void onReject() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comment", this.getComment(taskDefKey));
		map.put("onRejectResult", ApprovalConstants.ON_REJECT_RESULT);
		Events.postEvent("onRejectResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 关闭窗口
	 */
	public void onCancel() {
		this.bean.getOutStaffLeaveApprovalViewMainWin().onClose();
	}

	/**
	 * 获取传值
	 * 
	 * @throws ParseException
	 * @throws WrongValueException
	 */
	private void bindBean() {
		String procDefName = (String) arg.get("procDefName");
		this.bean.getOutStaffLeaveApprovalViewMainWin().setTitle(
				procDefName + "审批");

		oaBaseObject = (AtiOaBaseObject) arg.get("oaBaseObject");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			// 获取审批意见
			PubUtil.fillBeanFromPo(oaBaseObject, bean);
		}
		type = (String) arg.get("opType");
		if (ApprovalConstants.OP_TYPE_VIEW.equals(type)) {
			// 查看历史工单
			setButtonValid(true, false, false);
			setTextValid(true, true, true);
		} else {
			// 审批中弹框
			taskDefKey = (String) arg.get("taskDefKey");
			if ("modify".equals(taskDefKey)) {
				setButtonValid(true, false, false);
				setTextValid(false, false, false);
			} else {
				setButtonValid(false, true, true);
			}
			if ("deptLeaderAudit".equals(taskDefKey)) {
				this.bean.getSecondText().setRows(2);
				this.setTextValid(true, false, false);
				bean.getSecondText().setValue(null);
			}
			if ("hrAudit".equals(taskDefKey)) {
				this.bean.getThirdText().setRows(2);
				this.setTextValid(false, true, false);
				bean.getThirdText().setValue(null);
			}
			if ("hrLeaderAudit".equals(taskDefKey)) {
				this.bean.getFourthText().setRows(2);
				this.setTextValid(false, false, true);
				bean.getFourthText().setValue(null);
			}
		}

		taskId = (String) arg.get("taskId");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			List<Map<String, Object>> list = actRunTaskManager
					.getRuTasks(oaBaseObject.getProcInstId());
			if (null == list) {
				ZkUtil.showError("未知错误!", "错误信息");
				return;
			}
			if (list.size() == 0) {
				String psnjobIdTmp = oaBaseObject.getPsnjobIdModify();
				oaBaseObject.setPsnjobIdModify((oaBaseObject.getPsnjobIdHis()));
				oaBaseObject.setPsnjobIdHis(psnjobIdTmp);
			}

			// 获取历史数据展示
			String outStaffId = oaBaseObject.getOutStaffId();
			if (!StrUtil.isNullOrEmpty(outStaffId)) {
				outStaffInfo.setOutStaffId(Long.parseLong(outStaffId));
				outStaffInfo = uecOutStaffManager
						.findUecOutStaffInfoByOutStaffId(outStaffInfo);
				PubUtil.fillBeanFromPo(outStaffInfo, bean);
				bean.getPsnName().setValue(outStaffInfo.getPsnName());
				bean.getPsnCode().setValue(outStaffInfo.getPsnCode());
			}

			String psnjobIdHis = oaBaseObject.getPsnjobIdHis();
			if (!StrUtil.isNullOrEmpty(psnjobIdHis)) {
				uecPsnjob.setPsnjobId(Long.parseLong(psnjobIdHis));
				uecPsnjob = uecPsnjobManager.findUecPsnjobById(uecPsnjob);
				// 组织
				bean.getOrgName().setValue(
						uecOrgOrgsManager.getUecOrgOrgsNameByPkOrg(uecPsnjob
								.getPkOrg()));
				// 部门
				bean.getDeptName().setValue(
						uecOrgDeptManager.getUecOrgDeptNameByPkDept(uecPsnjob
								.getPkDept()));
				// 人员类别
				uecBdPsncl = new UecBdPsncl();
				uecBdPsncl.setPkPsncl(uecPsnjob.getPkPsncl());
				uecBdPsncl = customFilesManager
						.findUecUecBdPsnclByUecBdPsncl(uecBdPsncl);
				if (!StrUtil.isNullOrEmpty(uecBdPsncl)) {
					bean.getPsnclName().setValue(uecBdPsncl.getName());
				}
			}

			// 获取审批数据展示
			String psnjobId = oaBaseObject.getPsnjobIdModify();
			if (!StrUtil.isNullOrEmpty(psnjobId)) {
				uecPsnjob = UecPsnjob.newInstance();
				uecPsnjob.setPsnjobId(Long.parseLong(psnjobId));
				uecPsnjob = uecPsnjobManager.findUecPsnjobById(uecPsnjob);
				if (null != uecPsnjob) {
					PubUtil.fillBeanFromPo(uecPsnjob, bean);
					bean.getPkHrorg().setValue(
							uecOrgOrgsManager
									.getUecOrgOrgsNameByPkOrg(uecPsnjob
											.getPkOrg()));
					bean.getOutStaffPkDept().setValue(
							uecOrgDeptManager
									.getUecOrgDeptNameByPkDept(uecPsnjob
											.getPkDept()));
					// 生效日期
					bean.getEffectDate().setValue(
							DateUtil.patternStrToDate(uecPsnjob.getEnddate()));

					// 人员类别
					uecBdPsncl = new UecBdPsncl();
					uecBdPsncl.setPkPsncl(uecPsnjob.getPkPsncl());
					uecBdPsncl = customFilesManager
							.findUecUecBdPsnclByUecBdPsncl(uecBdPsncl);
					if (!StrUtil.isNullOrEmpty(uecBdPsncl)) {
						bean.getOutPsncl().setValue(uecBdPsncl.getName());
					}
				}
			}
		}

	}

	/**
	 * 获取审批意见
	 * 
	 * @param taskDefKey
	 * @return
	 */
	private String getComment(String taskDefKey) {
		if ("deptLeaderAudit".equals(taskDefKey)) {
			return this.bean.getSecondText().getValue();
		}
		if ("hrAudit".equals(taskDefKey)) {
			return this.bean.getThirdText().getValue();
		}
		if ("hrLeaderAudit".equals(taskDefKey)) {
			return this.bean.getFourthText().getValue();
		}
		return null;
	}

	/**
	 * 设置按钮
	 * 
	 * @param canEdit
	 * @param canApproval
	 * @param canReject
	 */
	private void setButtonValid(boolean canEdit, boolean canApproval,
			boolean canReject) {
		this.bean.getOkBtn().setVisible(canEdit);
		this.bean.getOkBtn().setDisabled(!canEdit);

		this.bean.getApprovalBtn().setVisible(canApproval);
		this.bean.getApprovalBtn().setDisabled(!canApproval);

		this.bean.getRejectBtn().setVisible(canReject);
		this.bean.getRejectBtn().setDisabled(!canReject);

	}

	/**
	 * 设置审批意见栏
	 * 
	 * @param secondCanEdit
	 * @param thirdCanEdit
	 * @param fourthCanEdit
	 */
	private void setTextValid(boolean secondCanEdit, boolean thirdCanEdit,
			boolean fourthCanEdit) {
		this.bean.getSecondText().setDisabled(!secondCanEdit);
		this.bean.getThirdText().setDisabled(!thirdCanEdit);
		this.bean.getFourthText().setDisabled(!fourthCanEdit);
	}

	/**
	 * 检测填入的参数是否为空
	 */
	public String checkUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getEffectDate().getValue())) {
			return "请选择生效日期";
		} else if (StrUtil.isNullOrEmpty(bean.getOutPsncl().getValue())) {
			return "请选择人员类别";
		} else if (StrUtil.isNullOrEmpty(bean.getTrnstype().getSelectedItem()
				.getValue())) {
			return "请选择离职业务类型";
		} else if (StrUtil.isNullOrEmpty(bean.getTrnsreason().getSelectedItem()
				.getValue())) {
			return "请选择离职原因";
		}
		return null;
	}

	/**
	 * 绑定Listbox
	 */
	public void bandListbox() {
		// 人员类别--PSNCL_PK_ORG
		ListboxUtils.rendererForEdit(bean.getPkPsncl(),
				NodeVoUtil.getDictionariesPsncl(UecConstants.PSNCL_PK_ORG));
		// 离职原因
		List<NodeVo> nodeVotrnsReasonList = new ArrayList<NodeVo>();
		String[][] trnsReason = { { "1001A1100000000012ZO", "终止劳动合同" },
				{ "1001A1100000000012ZR", "主动离职" },
				{ "1001A1100000000012ZS", "非主动离职" },
				{ "1001A1100000000012ZQ", "企业内部调动" },
				{ "1001A1100000001KKMYR", "离退休、退职" }, };
		for (int i = 0; i < trnsReason.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(trnsReason[i][j]);
				nodeVo.setName(trnsReason[i][j + 1]);
			}
			nodeVotrnsReasonList.add(nodeVo);
		}
		ListboxUtils
				.rendererForEdit(bean.getTrnsreason(), nodeVotrnsReasonList);
		// 离职业务类型--异动类型TRNSTYPE
		List<NodeVo> nodeVotrnstypeList = new ArrayList<NodeVo>();
		String[][] trnstype = { { "1002Z710000000008GSV", "离退休" },
				{ "1002Z710000000008GSW", "退职" },
				{ "1002Z710000000008GSX", "组织调动-到实业" },
				{ "1002Z710000000008PAW", "企业解除合同" },
				{ "1002Z710000000008GSZ", "员工解除合同" },
				{ "1001A110000000000R1W", "企业终止合同" },
				{ "1001A110000000000R1X", "员工终止合同" },
				{ "1001A110000000000R1Y", "死亡（在职）" },
				{ "1001A110000000000R1Z", "调出集团（不含成建制）" },
				{ "1001A110000000000R20", "成建制划出" },
				{ "1001A110000000000R21", "派遣制员工离职" },
				{ "1001A110000000000R22", "组织调动-到控股参股" },
				{ "1001A110000000000R24", "有偿协商解除合同" },
				{ "1001A110000000000R23", "有偿协商解除合同" } };
		for (int i = 0; i < trnstype.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(trnstype[i][j]);
				nodeVo.setName(trnstype[i][j + 1]);
			}
			nodeVotrnstypeList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getTrnstype(), nodeVotrnstypeList);
	}

}
